package com.stylefeng.guns.modular.customer.util;

import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.SpringContextHolder;
import com.stylefeng.guns.modular.customer.dao.CustomerCompanyDao;
import com.stylefeng.guns.modular.system.dao.CustomerCompanyManageMapper;
import com.stylefeng.guns.modular.system.model.CustomerCompany;
import com.stylefeng.guns.modular.system.model.CustomerCompanyManage;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomerUtil {

    /**
     * 判断编辑权限
     * @param customerCompanyId
     * @return
     */
    public static boolean validEditPermission(Integer customerCompanyId){
        //管理员
        if (ShiroKit.isAdmin()) {
            return true;
        }
        CustomerCompanyManageMapper customerCompanyManageMapper = SpringContextHolder.getBean(CustomerCompanyManageMapper.class);
        CustomerCompanyManage customerCompanyManage = customerCompanyManageMapper.selectById(customerCompanyId);
        if (customerCompanyManage == null) {
            return false;
        }

        if (customerCompanyManage.getSalesmanId().equals(ShiroKit.getUser().getId())) {
            return true;
        }

        //经理
        if (ShiroKit.hasRole("salesManager")){
            if (ObjectUtils.compare(ShiroKit.getUser().getDeptId(), customerCompanyManage.getDepartId()) == 0) {
                return true;
            }
        }
        return false;
    }

    public static void putAuthority(Map map, Integer customerCompanyId) {
        if (CustomerUtil.validEditPermission(customerCompanyId)) {
            map.put(Const.AUTHORITY_FIELD_NAME, 1);
        } else {
            map.put(Const.AUTHORITY_FIELD_NAME, -1);
        }
    }

    /**
     * 获取当前用户负责管理客户范围的集合
     * @return
     */
    public static List<Integer> getCustomerDataScope() {
        List<Integer> customerIds = new ArrayList<>();
        CustomerCompanyDao customerCompanyDao = SpringContextHolder.getBean(CustomerCompanyDao.class);
        //经理
        List<CustomerCompany> customerList;
        if (ShiroKit.hasRole("salesManager")) {
            customerList = customerCompanyDao.selectByDeptId(ShiroKit.getUser().getDeptId());
        }else{
            customerList = customerCompanyDao.selectBySalesmanId(ShiroKit.getUser().getId());
        }

        if (CollectionUtils.isEmpty(customerList)) {
            customerIds.add(-1);

        }else{
            for (CustomerCompany c : customerList) {
                customerIds.add(c.getId());
            }
        }
        return customerIds;
    }

}
